package com.service.impl;

import com.common.exception.db.UpdateException;
import com.dao.BillDao;
import com.entity.BillInfo;
import com.entity.MoneyInfo;
import com.service.BillService;
import com.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class BillServiceImpl implements BillService{
    @Autowired
    private BillDao dao;

    @Override
    @Transactional
    public MoneyInfo findUserMoney(Integer userId) {
        List<MoneyInfo> list = dao.findUserFreezeMoneyList(userId);
        for(MoneyInfo moneyInfo : list){
            int count = dao.updateFreezeMoneyStatus(moneyInfo.getFreezeId());
            if(count > 0){
                count = dao.updateUserMoney(userId,moneyInfo.getFreezeMoney());
                if(count == 0){
                    throw new UpdateException("修改失败");
                }
            }else{
                throw new UpdateException("修改失败");
            }
        }
        MoneyInfo info = dao.findUserMoney(userId);
        BigDecimal freezeMoney = dao.findUserFreezeMoney(userId);
        info.setFreezeMoney(freezeMoney);
        return info;
    }

    @Override
    public List<BillInfo> findBillList(Integer userId,Integer limit) {
        List<BillInfo> newList = new ArrayList<>();
        List<BillInfo> list = dao.findBillList(userId,limit);
        List<BillInfo> list1 = dao.findBillList1(userId,limit);
        for(BillInfo info :list1){
            list.add(info);
        }
        for(BillInfo info1:list){
            newList.add(info1);
        }
        return newList;
    }

    @Override
    public int  insertBill(Integer userId, BigDecimal money, Integer types, String description) {
        String uuid = UUIDUtil.get32UUID();
        return dao.insertBill(userId,money,types,description,uuid);
    }

}
